package com.itheima.ui;

import com.itheima.user.User;
import com.itheima.utils.VerifyCode;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

//创建 LoginJFrame 类 继承 JFrame 类
public class LoginJFrame extends JFrame {
    //用户列表
    ArrayList<User> userList = new ArrayList<>();

    //登录按钮
    JButton loginBtn = new JButton(new ImageIcon("image\\login\\登录按钮.png"));
    //注册按钮
    JButton registerBtn = new JButton(new ImageIcon("image\\login\\注册按钮.png"));

    //用户名
    JTextField jTextField = new JTextField();

    //密码
    JPasswordField jPasswordField = new JPasswordField();

    //验证码输入
    JTextField codeField = new JTextField();

    //生成验证码
    JLabel verificationCode = new JLabel();

    public LoginJFrame() { //创建空参构造并初始化界面窗口
        //读取本地用户信息
        this.userList = getUserList();

        initJFrame();
        initJFrameView();

        //设置窗口显示
        this.setVisible(true);
    }

    private static ArrayList<User> getUserList(){
        //读取磁盘的userList.txt文件
        ArrayList<User> list = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(new FileReader("user_list.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                String[] userInfoArr = line.split("&");
                String[] arr1 = userInfoArr[0].split("=");
                String[] arr2 = userInfoArr[1].split("=");
                list.add(new User(arr1[1], arr2[1]));
            }
        }catch (IOException e){
            e.printStackTrace();
        }

        return list;
    }

    private void initJFrameView() {


        registerBtn.setBounds(310, 350, 128, 47);
        registerBtn.setContentAreaFilled(false);//取消蓝色背景
        registerBtn.setBorderPainted(false);//取消边框
        this.getContentPane().add(registerBtn);


        //绑定点击注册按钮
        registerBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                new RegisterJFrame(userList);
            }
        });

        //绑定注册按钮鼠标按下抬起
        registerBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                registerBtn.setIcon(new ImageIcon("image\\login\\注册按下.png"));
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                registerBtn.setIcon(new ImageIcon("image\\login\\注册按钮.png"));
            }
        });

        loginBtn.setBounds(160, 350, 128, 47);
        loginBtn.setContentAreaFilled(false);//取消蓝色背景
        loginBtn.setBorderPainted(false);//取消边框
        this.getContentPane().add(loginBtn);

        //绑定登录按钮点击按钮
        loginBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                submitLogin();
            }
        });

        //绑定登录按钮鼠标按下抬起
        loginBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                loginBtn.setIcon(new ImageIcon("image\\login\\登录按下.png"));
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                loginBtn.setIcon(new ImageIcon("image\\login\\登录按钮.png"));
            }
        });

        //获取验证码显示
        verificationCode.setText(VerifyCode.getCode());
        verificationCode.setBounds(330, 290, 100, 40);
        verificationCode.setFont(new Font("", Font.ROMAN_BASELINE, 20));
        this.getContentPane().add(verificationCode);

        verificationCode.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                verificationCode.setText(VerifyCode.getCode());
            }
        });


        //验证码输入
        JLabel codeLabel = new JLabel(new ImageIcon("image\\login\\验证码.png"));
        codeLabel.setBounds(140, 290, 47, 40);
        this.getContentPane().add(codeLabel);

        codeField.setBounds(200, 290, 120, 40);
        codeField.setFont(new Font("", Font.ROMAN_BASELINE, 20));
        this.getContentPane().add(codeField);
        codeField.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {

            }

            @Override
            public void keyPressed(KeyEvent e) {

            }

            @Override
            public void keyReleased(KeyEvent e) {
                //绑定回车登录
                int keyCode = e.getKeyCode();
                if (keyCode == 10) {
                    submitLogin();
                }
            }
        });


        //显示密码
        JLabel passwordView = new JLabel(new ImageIcon("image\\login\\显示密码.png"));
        passwordView.setBounds(380, 250, 29, 18);
        this.getContentPane().add(passwordView);


        //密码
        JLabel passwordLabel = new JLabel(new ImageIcon("image\\login\\密码.png"));
        passwordLabel.setBounds(140, 240, 47, 40);
        this.getContentPane().add(passwordLabel);


        jPasswordField.setFont(new Font("", Font.ROMAN_BASELINE, 20));
        jPasswordField.setBounds(200, 240, 180, 40);

        this.getContentPane().add(jPasswordField);

        passwordView.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (jPasswordField.getEchoChar() == '*') {
                    jPasswordField.setEchoChar((char) 0); // 设置为0移除密码隐藏字符
                    passwordView.setIcon(new ImageIcon("image\\login\\显示密码按下.png"));
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                jPasswordField.setEchoChar('*');
                passwordView.setIcon(new ImageIcon("image\\login\\显示密码.png"));
            }
        });


        //用户名
        JLabel usernameLabel = new JLabel(new ImageIcon("image\\login\\用户名.png"));
        usernameLabel.setBounds(140, 190, 47, 40);
        this.getContentPane().add(usernameLabel);

        jTextField.setBounds(200, 190, 200, 40);
        jTextField.setFont(new Font("", Font.ROMAN_BASELINE, 20));
        this.getContentPane().add(jTextField);


        //设置背景
        JLabel bgImage = new JLabel(new ImageIcon("image\\login\\background.png"));
        bgImage.setBounds(60, 50, 470, 390);
        this.getContentPane().add(bgImage);


    }

    private void initJFrame() {
        //设置窗口大小
        this.setSize(600, 540);
        //设置窗口标题
        this.setTitle("拼图游戏 登录");

        //设置窗口置顶层
        this.setAlwaysOnTop(true);
        //设置窗口居中
        this.setLocationRelativeTo(null);
        //设置窗口关闭模式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        this.setLayout(null);


    }

    //获取用户信息
    private User getUserInfo(ArrayList<User> userList, String username, String password) {
        User result = new User();
        for (User user : userList) {
            String name = user.getUsername();
            String passw = user.getPassword();
            if (name.equals(username) && passw.equals(password)) {
                result.setUsername(name);
                result.setPassword(passw);
            }
        }

        return result;

    }

    //提交登录
    private void submitLogin() {
        String username = jTextField.getText();
        if (username.isEmpty()) {
            showDialog("用户名不能为空");
            return;
        }

        char[] password = jPasswordField.getPassword();
        if (password.length == 0) {
            showDialog("密码不能为空");
            return;
        }

        String code = codeField.getText();
        if (code.isEmpty()) {
            showDialog("验证码不能为空");
            return;
        }

        //判断用户信息
        if (getUserInfo(userList, username, String.valueOf(password)).getUsername() == null) {
            showDialog("用户名或密码错误");
            return;
        }
        //判断验证码
        if (!code.equalsIgnoreCase(verificationCode.getText())) {
            JOptionPane optionPane = new JOptionPane();
            optionPane.setMessage("验证码错误，请重新输入");
            JDialog dialog = optionPane.createDialog("提示");
            dialog.setAlwaysOnTop(true);
            dialog.setVisible(true);
            if (optionPane.getOptions() == null) {
                verificationCode.setText(VerifyCode.getCode());
                return;
            }
        }

        //验证通过
        this.setVisible(false);
        System.out.println("登录成功");
        new GameJFrame();
    }

    private void showDialog(String message) {
        JOptionPane optionPane = new JOptionPane();
        optionPane.setMessage(message);
        JDialog dialog = optionPane.createDialog("提示");
        dialog.setAlwaysOnTop(true);
        dialog.setVisible(true);
    }


}
